//
//  COServiceViewController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit
import IQKeyboardManagerSwift

class COServiceViewController: RCConversationViewController,UITextViewDelegate {
    
    var qaArr = [MarketQaModel]()
    
    private var textViewBottomConstraint: NSLayoutConstraint!   // 间距
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.enableAutoToolbar = false
        NotificationCenter.default.post(name: .NewUserRechargeNotification, object: nil, userInfo: ["type":1])
        NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":1])
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
        NotificationCenter.default.post(name: .NewUserRechargeNotification, object: nil, userInfo: ["type":0])
        NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":0])
    }
    
    lazy var navView :UIView = {
        let nav = UIView()
        return nav
    }()
    
    lazy var containView: UIView = {
        let con = UIView()
        con.backgroundColor = UIColor.white
        return con
    }()
    
    lazy var bgImg: UIImageView = {
        let nav = UIImageView()
        nav.image = KImaged("coco_main_bg")
        nav.contentMode = .scaleAspectFill
        nav.clipsToBounds = true
        return nav
    }()
    
    lazy var backBtn :UIButton = {
        let back = UIButton()
        back.setImage(KImaged("coco_base_fanhui"), for: .normal)
        back.addTap { [weak self] ges in
            guard let `self` = self else { return }
            self.navigationController?.popViewController(animated: true)
        }
        return back
    }()
    
    lazy var nameLbl:UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.pingfangFont(ofSize: PTW(16), weight: .medium)
        lbl.textColor = UIColor.white
        lbl.numberOfLines = 0
        lbl.textAlignment = .center
        lbl.text = "Customer service center"
        return lbl
    }()

    // 聊天容器
    lazy var inputToolbar: UIView = {
        let input = UIView()
        input.backgroundColor = UIColor.clear
        input.translatesAutoresizingMaskIntoConstraints = false
        return input
    }()
    
    // 输入框
    lazy var textView: GrowingTextView = {
        let txtView = GrowingTextView()
        txtView.delegate = self
        txtView.maxLength = 300
        txtView.maxHeight = PTW(70)
        txtView.minHeight = PTW(50)
        txtView.textColor = UIColor.colorWithHex("#7863A6", 1)
        txtView.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        txtView.layer.cornerRadius = PTW(25)
        txtView.layer.masksToBounds = true
        txtView.trimWhiteSpaceWhenEndEditing = true
        txtView.placeholder = "Write here"
        txtView.placeholderColor = UIColor.colorWithHex("#7863A6", 0.5)
        txtView.font = UIFont.pingfangFont(ofSize: PTW(15), weight: .medium)
        txtView.returnKeyType = .send
        txtView.enablesReturnKeyAutomatically = true
        txtView.translatesAutoresizingMaskIntoConstraints = false
        // 使用textContainerInset设置top、left、right
        txtView.textContainerInset = UIEdgeInsets(top: PTW(15), left: PTW(15), bottom: 0, right: PTW(10))
        //当光标在最后一行时，始终显示低边距，需使用contentInset设置bottom.
        txtView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: PTW(10), right: 0)
        //防止在拼音打字时抖动
        txtView.layoutManager.allowsNonContiguousLayout = false
        return txtView
    }()
    
    // 礼物按钮
    lazy var giftBtn: UIButton = {
        let gift = UIButton(type: .custom)
        gift.setImage(KImaged("coco_msg_picture"), for: .normal)
        gift.translatesAutoresizingMaskIntoConstraints = false
        gift.addTarget(self, action: #selector(giftAction), for: .touchUpInside)
        return gift
    }()

    lazy var iconImg: UIImageView = {
        let nav = UIImageView()
        nav.contentMode = .scaleAspectFill
        nav.layer.cornerRadius = 20
        nav.clipsToBounds = true
        nav.image = KImaged("coco_msg_cusService")
        return nav
    }()
    
    lazy var tagView: COServiceTagsView = {
        let tagView = COServiceTagsView(frame: .zero)
        tagView.qaArr = self.qaArr
        tagView.sureBlock = {[weak self] model in
            self?.selectMarkeyQa(model: model)
        }
        return tagView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        conversationMessageCollectionView.backgroundColor = .clear
        //隐藏输入框并修改背景色
        if (self.chatSessionInputBarControl != nil){
            self.chatSessionInputBarControl.isHidden = true
            if (self.chatSessionInputBarControl.safeAreaView != nil){
                self.chatSessionInputBarControl.safeAreaView.isHidden = true
            }
        }
        xl_prefersNavigationBarHidden = true
        xl_interactivePopMaxAllowedInitialDistanceToLeftEdge = PTW(200)
        
        self.view.addSubview(self.bgImg)
        self.bgImg.addSubview(self.containView)
        self.bgImg.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.containView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(KStatusAndNavBarHeight + PTW(10))
        }
        self.view.sendSubviewToBack(self.bgImg)
        // 隐藏工具栏
        chatSessionInputBarControl.isHidden = true
        conversationMessageCollectionView.contentInset = UIEdgeInsets(top: PTW(10), left: PTW(0), bottom: PTW(0), right: PTW(0))
        self.setUpNavView()
        
        self.view.addSubview(self.tagView)
        self.tagView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(PTW(13))
            make.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-PTW(70)-KSafeBottomMargin)
            make.height.equalTo(PTW(80))
        }
        
        // 设置工具栏
        setToolView()
        register(COConversationListCell.self, forMessageClass: RCTextMessage.self)
        register(COConversationListCell.self, forMessageClass: RCImageMessage.self)
        register(COConversationListCell.self, forMessageClass: COGiftContent.self)
        register(COConversationListCell.self, forMessageClass: COVideoContent.self)
        self.setNeedsStatusBarAppearanceUpdate()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containView.clipsCorners(corners: [.topLeft,.topRight], radius: PTW(30))
    }
    
    // MARK: ----------------------- 设置导航栏 -------------------------
    func setUpNavView(){
        view.addSubview(navView)
        navView.addSubview(backBtn)
        navView.addSubview(iconImg)
        navView.addSubview(nameLbl)
        navView.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(KStatusAndNavBarHeight)
        }
        backBtn.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.size.equalTo(PTW(44))
            make.bottom.equalToSuperview()
        }
        iconImg.snp.makeConstraints { make in
            make.leading.equalTo(backBtn.snp.trailing).offset(PTW(20))
            make.size.equalTo(PTW(40))
            make.centerY.equalTo(backBtn)
        }
        nameLbl.snp.makeConstraints { make in
            make.leading.equalTo(iconImg.snp.trailing).offset(PTW(10))
            make.centerY.equalTo(iconImg)
        }
    }
    
    // MARK: ----------------------- 设置工具栏 -------------------------
    func setToolView(){
        conversationMessageCollectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(inputToolbar)
        inputToolbar.addSubview(textView)
        inputToolbar.addSubview(giftBtn)
        
        let collectionBottomConstraint = conversationMessageCollectionView.bottomAnchor.constraint(equalTo: inputToolbar.topAnchor,constant: -PTW(80))
        collectionBottomConstraint.priority = UILayoutPriority(600)
        NSLayoutConstraint.activate([
            conversationMessageCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            conversationMessageCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            conversationMessageCollectionView.topAnchor.constraint(equalTo: view.topAnchor,constant: KStatusAndNavBarHeight + PTW(10)),
            collectionBottomConstraint
        ])
        
        // *** Autolayout ***
        let topConstraint = textView.topAnchor.constraint(equalTo: inputToolbar.topAnchor, constant: PTW(10))
        topConstraint.priority = UILayoutPriority(999)
        NSLayoutConstraint.activate([
            inputToolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            inputToolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            inputToolbar.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            topConstraint
        ])

        if #available(iOS 11, *) {
            textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: inputToolbar.safeAreaLayoutGuide.bottomAnchor,constant: -PTW(10))
            NSLayoutConstraint.activate([
                textView.leadingAnchor.constraint(equalTo: inputToolbar.safeAreaLayoutGuide.leadingAnchor, constant: PTW(20)),
                textView.trailingAnchor.constraint(equalTo: inputToolbar.safeAreaLayoutGuide.trailingAnchor, constant: -PTW(90)),
                textViewBottomConstraint
                ])
        } else {
            textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: inputToolbar.bottomAnchor,constant: -PTW(10))
            NSLayoutConstraint.activate([
                textView.leadingAnchor.constraint(equalTo: inputToolbar.leadingAnchor, constant: PTW(20)),
                textView.trailingAnchor.constraint(equalTo: inputToolbar.trailingAnchor, constant: -PTW(90)),
                textViewBottomConstraint
                ])
        }
        
        let bottomConstraint = giftBtn.bottomAnchor.constraint(equalTo: textView.bottomAnchor)
        let trailingConstraint = giftBtn.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -PTW(20))
        NSLayoutConstraint.activate([
            giftBtn.heightAnchor.constraint(equalToConstant: PTW(50)),
            giftBtn.widthAnchor.constraint(equalToConstant: PTW(50)),
            bottomConstraint,
            trailingConstraint
            ])
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(chatEndEditing), name: NSNotification.Name("chatEndEditingNotice"), object: nil)
    }
    
    @objc private func chatEndEditing(){
        self.view.endEditing(true)
    }
    
    @objc private func keyboardWillChangeFrame(_ notification: Notification) {
        if let endFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            var keyboardHeight = UIScreen.main.bounds.height - endFrame.origin.y
            if #available(iOS 11, *) {
                if keyboardHeight > 0 {
                    keyboardHeight = keyboardHeight - view.safeAreaInsets.bottom
                }
            }
            textViewBottomConstraint.constant = -keyboardHeight - PTW(10)
            view.layoutIfNeeded()
            uploadFrameWithConversations()
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: ---------------- 图片点击  ---------------
    @objc func giftAction(){
        
    }
}

//MARK: ---------------- 文本增长代理 ------------------
extension COServiceViewController {
    
    func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) {
        UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in
            self.view.layoutIfNeeded()
            self.uploadFrameWithConversations()
        }, completion: nil)
    }
    
    func uploadFrameWithConversations() {
        if conversationDataRepository.count > 0{
            let indexPath = IndexPath(item: conversationDataRepository.count - 1, section: 0)
            self.conversationMessageCollectionView.scrollToItem(at: indexPath, at: .bottom, animated: false)
        }
    }
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 发送键&回车键处理
        if (text == "\n") {
            self.sendMessageWithText(textView.text)
            return false
        }
        return true
    }
    
    //MARK: --------------- 发送文本消息 --------------
    func sendMessageWithText(_ message:String){
        guard let user = COUserInfoManager.shared.curUser else {return}
        let textMessage = RCTextMessage(content: message)
        let userInfo = RCUserInfo(userId: user.rcUserId, name: user.userResponse.nickName, portrait: user.userResponse.profilePhoto)
        textMessage.senderUserInfo = userInfo
        RCIMClient.shared().sendMessage(.ConversationType_PRIVATE, targetId: self.targetId, content: textMessage, pushContent: "Received a new message", pushData: nil) { (messageId) in
            DispatchQueue.main.async {
                let message = RCMessage(type: .ConversationType_PRIVATE, targetId: self.targetId, direction: .MessageDirection_SEND, content: textMessage)
                let model = RCMessageModel(message: message)
                self.conversationDataRepository.add(model as Any)
                let indexPath = IndexPath(item: self.conversationDataRepository.count - 1, section: 0)
                self.conversationMessageCollectionView.insertItems(at: [indexPath])
                self.conversationMessageCollectionView.scrollToItem(at: indexPath, at: .bottom, animated: false)
                self.textView.text = nil
            }
        } error: { (errorCode, messageId) in
            UIToolHelper.makeToast("Failed to send")
        }
    }
    
    //MARK: --------------- 客服消息  -----------------
    func selectMarkeyQa(model:MarketQaModel){
        guard let user = COUserInfoManager.shared.curUser else {return}
        let systemMsg = RCTextMessage(content: model.problem)
        let userInfo = RCUserInfo(userId: user.rcUserId, name: user.userResponse.nickName, portrait: user.userResponse.profilePhoto)
        systemMsg.senderUserInfo = userInfo
        RCIMClient.shared().insertOutgoingMessage(self.conversationType, targetId: self.targetId, sentStatus: .SentStatus_SENT, content: systemMsg)
        let message = RCMessage(type: self.conversationType, targetId: self.targetId, direction: .MessageDirection_SEND, content: systemMsg)
        self.appendAndDisplay(message)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
            let responseMsg = RCTextMessage(content: model.answer)
            RCIMClient.shared().insertIncomingMessage(self.conversationType, targetId: self.targetId, senderUserId: self.targetId, receivedStatus: .ReceivedStatus_READ, content: responseMsg)
            let responsemessage = RCMessage(type: self.conversationType, targetId: self.targetId, direction: .MessageDirection_RECEIVE, content: responseMsg)
            self.appendAndDisplay(responsemessage)
        })
    }
}
